import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'typeof/common_title_edit_with_underline_typeof.dart';

/// 通用标题编辑框带选中变化线组件
///
/// @author: zengxiangxi
/// @createTime: 1/18/21 10:06 PM
/// @specialDemand:
class CommonTitleEditWithUnderlineWidget extends StatefulWidget {

  final TextEditingController controller;

  ///下划线边距
  final EdgeInsetsGeometry lineMargin;

  ///容器高度
  final double height;

  ///线高度
  final double lineHeight;

  ///线未选中颜色
  final Color lineUnselectColor;

  ///线选中颜色
  final Color lineSelectedColor;

  ///左组件
  final Widget leftWidget;

  ///右组件
  final Widget rightWidget;

  ///头标题
  final String title;

  ///头标题样式
  final TextStyle titleTextStyle;

  ///提示语文字
  final String hintText;

  ///提示语样式
  final TextStyle hintTextStyle;

  ///标题宽度
  final double titleWidth;

  ///编辑文字样式
  final TextStyle editTextStyle;

  ///改变回调
  final CommonTitleEditEditAndValueChangedCallback onChanged;

  ///点击
  final CommonTitleNavigatorPushCallback onTap;

  ///解析跳转返回值
  final CommonTitlePopResultDecodeCallback onDecodeResult;

  ///最小行数
  final int minLines;

  ///最大行数
  final int maxLines;

  ///中字极限
  final int maxZHCharLimit;

  ///极限字数回调
  final ValueChanged<int> limitCharFunc;

  ///限制
  final List<TextInputFormatter> inputFormatters;

  ///初始内容
  final String initContent;

  ///初始值
  final dynamic initValue;

  ///只读
  final bool readOnly;

  ///maxLength
  final int maxLength;

  ///标题右间距
  final double titleMarginRight;

  ///自动dispose
  final bool autoDispose;

  ///键盘的监听
  final bool autofocus;


  final TextInputType keyboardType;

  final Function(Widget titleWidget, Widget textFieldWidget,Widget leftWidget,Widget rightWidget) customWidget;

  const CommonTitleEditWithUnderlineWidget({
    Key key,
    @required this.lineMargin,
    @required this.hintText,
    @required this.height,
    @required this.lineHeight,
    @required this.lineUnselectColor,
    @required this.lineSelectedColor,
    @required this.leftWidget,
    @required this.rightWidget,
    @required this.title,
    @required this.titleTextStyle,
    @required this.hintTextStyle,
    @required this.titleWidth,
    @required this.editTextStyle,
    this.onChanged,
    this.onTap,
    this.onDecodeResult,
    this.maxLines = 1,
    this.minLines,
    this.maxZHCharLimit,
    this.limitCharFunc,
    this.inputFormatters,
    this.initContent,
    this.readOnly,
    this.initValue,
    this.maxLength,
    this.customWidget, this.controller,this.keyboardType, this.titleMarginRight, this.autoDispose,this.autofocus
  }) : super(key: key);

  @override
  _CommonTitleEditWithUnderlineWidgetState createState() =>
      _CommonTitleEditWithUnderlineWidgetState();
}

class _CommonTitleEditWithUnderlineWidgetState
    extends State<CommonTitleEditWithUnderlineWidget> {
  TextEditingController _editingController;

  FocusNode _focusNode;

  ValueNotifier<bool> _isShowFocusLineNotifier;

  dynamic value;


  @override
  void initState() {
    super.initState();
    _editingController = (widget.controller ?? TextEditingController())..text = widget?.initContent;
    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode?.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
    value = widget?.initValue;
  }

  @override
  void dispose() {
    if(widget.autoDispose??true){
      _editingController?.dispose();
    }
    _focusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          height: widget.height,
          child: widget.customWidget
              ?.call(_toTitleWidget(), _toTextFieldWidget(),widget.leftWidget,widget.rightWidget) ??
              Row(
                children: <Widget>[
                  widget.leftWidget ?? Container(),
                  _toTitleWidget(),
                  SizedBox(
                    width: 2,
                  ),
                  Expanded(
                    child: _toTextFieldWidget(),
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  widget.rightWidget ?? Container(),
                ],
              ),
        ),
        ValueListenableBuilder(
          builder: (_, value, Widget child) {
            return AnimatedContainer(
                height: widget.lineHeight ?? 1,
                margin: widget.lineMargin,
                duration: DEFAULT_ANIM_DURATION,
                color: value
                    ? widget.lineSelectedColor
                    : widget.lineUnselectColor);
          },
          valueListenable: _isShowFocusLineNotifier,
        )
      ],
    );
  }

  Widget _toTextFieldWidget() {
    return VgTextField(
      controller: _editingController,
      focusNode: _focusNode,
      style: widget.editTextStyle,
      readOnly: widget.readOnly ?? (widget?.onTap != null ? true : false),
      maxLines: widget?.maxLines,
      minLines: widget?.minLines,
      maxLength: widget?.maxLength,
      autofocus: widget?.autofocus ??false,
      inputFormatters: widget?.inputFormatters,
      maxLimitLength: widget?.maxZHCharLimit,
      limitCallback: widget?.limitCharFunc,
      keyboardType: widget?.keyboardType,
      decoration: InputDecoration(
        border: InputBorder.none,
        counterText: "",
        contentPadding: const EdgeInsets.only(bottom: 0),
        hintText: widget.hintText,
        hintStyle: widget.hintTextStyle,
      ),
      onChanged: (String editText) {
        _onChanged(editText?.trim(), value);
      },
      onTap: () async {
        if (widget?.onTap != null) {
          dynamic result =
          await widget.onTap(_editingController?.text?.trim(), value);
          if (result == null || widget.onDecodeResult == null) {
            return;
          }
          EditTextAndValue decodeResult = widget.onDecodeResult(result);
          if (decodeResult == null) {
            return;
          }
          _editingController.text = decodeResult.editText;
          value = decodeResult.value;
          _onChanged(_editingController?.text?.trim(), value);
        }
      },
    );
  }

  Container _toTitleWidget() {
    return Container(
      width: widget.titleWidth,
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(right: widget.titleMarginRight??0),
      child: Text(widget.title,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: widget.titleTextStyle),
    );
  }

  void _onChanged(String editText, dynamic value) {
    if (widget?.onChanged != null) {
      widget.onChanged(editText, value);
    }
  }
}
